/**
 * created by uu, 16/09/26
 * #                                                   #
 * #                       _oo0oo_                     #
 * #                      o8888888o                    #
 * #                      88" . "88                    #
 * #                      (| -_- |)                    #
 * #                      0\  =  /0                    #
 * #                    ___/`---'\___                  #
 * #                  .' \\|     |# '.                 #
 * #                 / \\|||  :  |||# \                #
 * #                / _||||| -:- |||||- \              #
 * #               |   | \\\  -  #/ |   |              #
 * #               | \_|  ''\---/''  |_/ |             #
 * #               \  .-\__  '-'  ___/-. /             #
 * #             ___'. .'  /--.--\  `. .'___           #
 * #          ."" '<  `.___\_<|>_/___.' >' "".         #
 * #         | | :  `- \`.;`\ _ /`;.`/ - ` : | |       #
 * #         \  \ `_.   \_ __\ /__ _/   .-` /  /       #
 * #     =====`-.____`.___ \_____/___.-`___.-'=====    #
 * #                       `=---='                     #
 * #     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   #
 * #                                                   #
 * #               佛祖保佑         永无BUG            #
 * #                                                   #
 */
package com.hemaapp.yjnh.activity;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.util.XtomWindowSize;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.uu.utils.uuUtils;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.HemaWebView;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseFragmentActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.ReplyAdapter;
import com.hemaapp.yjnh.bean.AttributeItems;
import com.hemaapp.yjnh.bean.BlogDetail;
import com.hemaapp.yjnh.bean.BlogDetailBySpec;
import com.hemaapp.yjnh.bean.BlogSpecName;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.ImgItemsBean;
import com.hemaapp.yjnh.bean.Reply;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.utils.LoginUtil;
import com.hemaapp.yjnh.view.FlowLayout;
import com.hemaapp.yjnh.view.ImageCarouselBanner;
import com.hemaapp.yjnh.view.NumberSelectorLayout;
import com.hemaapp.yjnh.view.ShareDialog;
import com.hemaapp.yjnh.view.YjnhListView;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.media.UMImage;

/**
 * 实体类商品详情：包括平台自营和第三方商家
 * 粮库、特产、有机、地标使用此模板
 */
public class CmnProductionDetailActivity extends BaseFragmentActivity implements OnClickListener {

    private final static int REQUEST_ADD_CART = 0x01;//添加到购物车
    private final static int REQUEST_GO_CART = 0x02;//去购物车

    private TextView titleText;
    private ImageButton titleLeft;
    private Button titleRightBtn;
    private ImageView titleShare;
    private ImageView titleLove;

    private ScrollView scrollview;
    private FrameLayout layoutHead;
    private ImageCarouselBanner imageCarouselBanner;
    private TextView tv_A;//
    private TextView tv_organic;//有机
    private ImageView iv_muslim;//清真
    private TextView tvGoodsName;
    ;//商品名称
    private TextView tvPriceNew;//现在价格
    private TextView tvPriceOld;//之前的价格
    private TextView tvSpec;//规格
    private TextView tvCouponsCount;//可用粮票数
    private TextView tvTuihuo;
    private TextView tvFreight;
    private TextView tvStore;
    private TextView tvSellCount;
    private LinearLayout layoutAttribute;
    private TextView tvAttribute;
    private TextView tvAttributeHint;
    private LinearLayout layoutMerchant;
    private ImageView ivMerchantAvatar;
    private TextView tvMerchantName;
    private RatingBar ratingBar;
    private ImageView iv_merchant_drawright;

    private TextView rbt_details;//商品详情
    private TextView rbt_reply;//用户口碑，用于动态填写评论数量
    private View details_line;
    private View reply_line;//商品详情和用户口碑下面的下划线
    private View content_detail;

    private LinearLayout ll_return_top;
    private ImageView ivConsult;
    private TextView tv_buycontent;
    private FrameLayout layoutGoCart;
    private TextView tvUnreadCount;
    private TextView tvAddCart;
    private TextView tvBuy;
    private ImageView attrImage;//属性选择dialog中的商品图片
    private TextView attrPrice;//属性选择dialog中的商品价格
    private NumberSelectorLayout numberSelector;
    private FlowLayout flowLayout;//属性二

    //详情
    private LinearLayout layoutProperty;
    private TextView tvQuestion;
    private HemaWebView webview;
    //口碑
    private XtomRefreshLoadmoreLayout refreshlayout;
    private YjnhListView listView;

    private String mBlogId;//当前商品的id
    private BlogDetail blog;//当前商品
    private BlogDetailBySpec detailBySpec;
    private User user;
    private int cart_count = 0;//购物车内的商品数量
    //商品详情和口碑
    private ArrayList<AttributeItems> attributes = new ArrayList<>();
    private Integer currentPage = 0;
    private ReplyAdapter replyAdapter;
    private ArrayList<Reply> replies = new ArrayList<Reply>();
    private int buyCount = 1;
    private Dialog attrDialog;
    private String specOne = "";//一级规格名称
    private String specTwo = "";//二级规格名称
    private ArrayList<BlogSpecName> specNames1 = new ArrayList<>();
    private ArrayList<BlogSpecName> specNames2 = new ArrayList<>();
    private ArrayList<TextView> specText1 = new ArrayList<>();
    private ArrayList<TextView> specText2 = new ArrayList<>();
    private LoginUtil.LoginCallBack loginCallBack;
    private AttrSelectCallBack attrSelectCallBack;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_production_detail);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        init();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void getExras() {
        mBlogId = mIntent.getStringExtra("blog_id");
        if (isNull(mBlogId)) {
            XtomToastUtil.showShortToast(mContext, "获取商品信息失败，请稍后再试");
            finish();
        }
    }

    @Override
    protected void findView() {
        titleText = (TextView) findViewById(R.id.title_text);
        titleLeft = (ImageButton) findViewById(R.id.title_left_btn);
        titleRightBtn = (Button) findViewById(R.id.title_right_btn);
        titleLove = (ImageView) findViewById(R.id.title_right_img);
        titleShare = (ImageView) findViewById(R.id.title_right_img2);

        scrollview = (ScrollView) findViewById(R.id.scrollview);
        layoutHead = (FrameLayout) findViewById(R.id.layout_head);
        imageCarouselBanner = (ImageCarouselBanner) findViewById(R.id.image_carousel_banner);
        tv_A = (TextView) findViewById(R.id.tv_A);
        tv_organic = (TextView) findViewById(R.id.tv_organic);
        iv_muslim = (ImageView) findViewById(R.id.iv_muslim);
        rbt_details = (TextView) findViewById(R.id.rbt_details);
        rbt_reply = (TextView) findViewById(R.id.rbt_reply);
        tvGoodsName = (TextView) findViewById(R.id.tv_goods_name);
        tvPriceNew = (TextView) findViewById(R.id.tv_price_new);
        tvPriceOld = (TextView) findViewById(R.id.tv_price_old);
        tvTuihuo = (TextView) findViewById(R.id.tv_tuihuo);
        tvSpec = (TextView) findViewById(R.id.tv_spec);
        tvCouponsCount = (TextView) findViewById(R.id.tv_coupons_count);
        tvFreight = (TextView) findViewById(R.id.tv_freight);
        tvStore = (TextView) findViewById(R.id.tv_store);
        tvSellCount = (TextView) findViewById(R.id.tv_sell_count);
        layoutAttribute = (LinearLayout) findViewById(R.id.layout_attribute);
        tvAttribute = (TextView) findViewById(R.id.tv_attribute);
        tvAttributeHint = (TextView) findViewById(R.id.tv_attribute_hint);
        layoutMerchant = (LinearLayout) findViewById(R.id.layout_merchant);
        ivMerchantAvatar = (ImageView) findViewById(R.id.iv_merchant_avatar);
        tvMerchantName = (TextView) findViewById(R.id.tv_merchant_name);
        ratingBar = (RatingBar) findViewById(R.id.ratingBar);
        iv_merchant_drawright = (ImageView) findViewById(R.id.iv_merchant_drawright);

        details_line = findViewById(R.id.details_line);//商品详情下面的下划线
        reply_line = findViewById(R.id.reply_line);//用户口碑下面的下划线
        content_detail = findViewById(R.id.content_detail);

        ivConsult = (ImageView) findViewById(R.id.iv_consult);
        tv_buycontent = (TextView) findViewById(R.id.tv_buycontent);
        layoutGoCart = (FrameLayout) findViewById(R.id.layout_go_cart);
        tvUnreadCount = (TextView) findViewById(R.id.tv_unread_count);
        tvAddCart = (TextView) findViewById(R.id.tv_add_cart);
        tvBuy = (TextView) findViewById(R.id.tv_buy);
        ll_return_top = (LinearLayout) findViewById(R.id.ll_return_top);//回到顶部

        layoutProperty = (LinearLayout) findViewById(R.id.layout_property);
        tvQuestion = (TextView) findViewById(R.id.tv_question);
        webview = (HemaWebView) findViewById(R.id.webview);

        refreshlayout = (XtomRefreshLoadmoreLayout) findViewById(R.id.refreshLoadmoreLayout);
        listView = (YjnhListView) findViewById(R.id.listview);
        listView.setFocusable(false);
    }

    @Override
    protected void setListener() {
        titleText.setText("商品详情");
        titleLeft.setOnClickListener(this);
        titleRightBtn.setVisibility(View.GONE);
        titleLove.setOnClickListener(this);
        titleShare.setImageResource(R.drawable.share);

        titleShare.setOnClickListener(this);
        layoutMerchant.setOnClickListener(this);
        iv_merchant_drawright.setOnClickListener(this);
        ll_return_top.setOnClickListener(this);
        ivConsult.setOnClickListener(this);
        layoutGoCart.setOnClickListener(this);
        tvAddCart.setOnClickListener(this);
        tvBuy.setOnClickListener(this);
        layoutAttribute.setOnClickListener(this);

        rbt_details.setOnClickListener(this);
        rbt_reply.setOnClickListener(this);
        if (blog != null) {
            titleLove.setVisibility(View.VISIBLE);
            titleShare.setVisibility(View.VISIBLE);
            setData();
        }else {
            titleLove.setVisibility(View.INVISIBLE);
            titleShare.setVisibility(View.INVISIBLE);
        }
        initWebView();
        //详情
        tvQuestion.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, QuestionActivity.class);
                intent.putExtra("QQ", blog.getQq());
                intent.putExtra("blog_id", blog.getId());
                startActivity(intent);
            }
        });
        //口碑
        refreshlayout.setOnStartListener(new OnStartListener() {

            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                init();
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                currentPage++;
                replyList(currentPage.toString());
            }
        });
    }

    /**
     * 初始化webview
     */
    private void initWebView() {
        // 支持javascript
        webview.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放
        webview.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        webview.getSettings().setBuiltInZoomControls(false);
        // 扩大比例的缩放
        webview.getSettings().setUseWideViewPort(true);
        // 自适应屏幕
        webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
        webview.getSettings().setLoadWithOverviewMode(true);
        // 取消显示滚动条
        webview.setVerticalScrollBarEnabled(false);
        webview.setHorizontalScrollBarEnabled(false);
        webview.setFocusable(false);
    }

    private void init() {
        currentPage = 0;
        String token = "";
        if (user != null) {
            token = user.getToken();
            getNetWorker().getCartCount(token);
        }
        getNetWorker().getBlogDetail(token, mBlogId);
        getNetWorker().getBlogSpecName(mBlogId, "");
    }

    private void initImagePager() {
        ArrayList<String> urls = new ArrayList<>();
        for (ImgItemsBean item : blog.getImgItems()) {
            urls.add(item.getImgurl());
        }
        imageCarouselBanner.getLayoutParams().height = XtomWindowSize.getWidth(mContext);
        layoutHead.getLayoutParams().height = XtomWindowSize.getWidth(mContext);
        imageCarouselBanner.onInstance(mContext, urls, R.drawable.ad_show_indicator,
                new ImageCarouselBlogClickListener(mContext, (ArrayList<ImgItemsBean>) blog.getImgItems()));
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
            case CART_COUNT:
            case REPLY_LIST:
            case CART_ADD:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
            case REPLY_LIST:
            case CART_COUNT:
            case BLOG_SPECNAME_GET:
            case CART_ADD:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
                HemaArrayResult<BlogDetail> bResult = (HemaArrayResult<BlogDetail>) baseResult;
                blog = bResult.getObjects().get(0);
                if (blog == null) {
                    XtomToastUtil.showShortToast(mContext, "获取商品信息失败，请稍后再试");
                    finish();
                }else {
                    titleLove.setVisibility(View.VISIBLE);
                    titleShare.setVisibility(View.VISIBLE);
                    initImagePager();
                    setData();
                    initPropertyList();//商品属性
                    replyList(currentPage.toString());//获取口碑列表
                }
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                String oper = netTask.getParams().get("oper");
                // 操作	1添加 ，2取消 ;3：清空
                if (oper.equals("1")) {
                    XtomToastUtil.showShortToast(mContext, "添加收藏成功!");
                    titleLove.setImageResource(R.drawable.star_while);
                    ScaleAnimation scaleAnimation = new ScaleAnimation(0.0f, 1.4f, 0.0f, 1.4f,
                            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    scaleAnimation.setDuration(300);//设置动画持续时间
                    titleLove.startAnimation(scaleAnimation);
                    blog.setCollectflag("1");
                } else {
                    XtomToastUtil.showShortToast(mContext, "取消收藏成功!");
                    titleLove.setImageResource(R.drawable.star_while_stroke);
                    blog.setCollectflag("0");
                }
                break;
            case REPLY_LIST:
                String page = netTask.getParams().get("page");
                HemaPageArrayResult<Reply> nResult = (HemaPageArrayResult<Reply>) baseResult;
                if (nResult == null || nResult.getObjects() == null)
                    return;
                ArrayList<Reply> replies = nResult.getObjects();
                if ("0".equals(page)) {// 刷新
                    refreshlayout.refreshSuccess();
                    this.replies.clear();
                    this.replies.addAll(replies);
                } else {// 更多
                    refreshlayout.loadmoreSuccess();
                    if (replies.size() > 0)
                        this.replies.addAll(replies);
                    else {
                        refreshlayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                refreshData();
                break;
            case CART_COUNT:
                HemaArrayResult<String> sResult = (HemaArrayResult<String>) baseResult;
                if (sResult == null || sResult.getObjects() == null)
                    return;
                ArrayList<String> strings = sResult.getObjects();
                if (strings.size() > 0) {
                    if (isNull(strings.get(0))) {
                        tvUnreadCount.setVisibility(View.INVISIBLE);
                        return;
                    } else {
                        cart_count = Integer.parseInt(strings.get(0));
                        if (cart_count == 0) {
                            tvUnreadCount.setVisibility(View.INVISIBLE);
                        } else {
                            tvUnreadCount.setVisibility(View.VISIBLE);
                            if (cart_count > 99)
                                tvUnreadCount.setText("99+");
                            else
                                tvUnreadCount.setText(cart_count + "");
                        }
                    }
                } else
                    tvUnreadCount.setVisibility(View.INVISIBLE);
                break;
            case BLOG_SPECNAME_GET:
                HemaArrayResult<BlogSpecName> sResult1 = (HemaArrayResult<BlogSpecName>) baseResult;
                if (sResult1 == null || sResult1.getObjects() == null)
                    return;
                String spec_name = netTask.getParams().get("spec_name");
                if (isNull(spec_name)) {//一级规格
                    specNames1.clear();
                    specNames1.addAll(sResult1.getObjects());
                } else {
                    specNames2.clear();
                    specNames2.addAll(sResult1.getObjects());
//                    specNames2.get(0).setChecked(true);
//                    specTwo = specNames2.get(0).getTwo_specname();
//                    getNetWorker().getBlogBySpec(blog_id, specOne, specTwo);
                    if (flowLayout != null) {
                        flowLayout.removeAllViews();
                        specText2.clear();
                        int oneDp = BaseUtil.dip2px(mContext, 1);
                        LinearLayout.LayoutParams lp0 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        lp0.setMargins(oneDp * 5, 0, oneDp * 5, 0);
                        for (BlogSpecName spec : specNames2) {
                            TextView tv = new TextView(mContext);
                            tv.setText(spec.getTwo_specname());
                            tv.setPadding(oneDp * 15, oneDp * 3, oneDp * 15, oneDp * 3);
                            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                            tv.setTextColor(Color.parseColor("#383838"));
                            tv.setGravity(Gravity.CENTER_VERTICAL);
                            tv.setTag(spec);
                            tv.setSingleLine();
                            if (spec.isChecked()) {
                                tv.setBackgroundColor(Color.parseColor("#ffae40"));
                                tv.setTextColor(Color.parseColor("#ffffff"));
                                tvAttributeHint.setText("您当前选择的为："+specOne+"，"+specTwo);
                            } else {
                                tv.setBackgroundResource(R.drawable.shape_editor);
                                tv.setTextColor(Color.parseColor("#383838"));
                            }
                            tv.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    BlogSpecName spec2 = (BlogSpecName) v.getTag();
                                    specTwo = spec2.getTwo_specname();
                                    for (int i = 0; i < specNames2.size(); i++) {
                                        if (specNames2.get(i).getTwo_specname().equals(spec2.getTwo_specname())) {
                                            specNames2.get(i).setChecked(true);
                                            specText2.get(i).setBackgroundColor(Color.parseColor("#ffae40"));
                                            specText2.get(i).setTextColor(Color.parseColor("#ffffff"));
                                            tvAttributeHint.setText("您当前选择的为："+specOne+"，"+specTwo);
                                            getNetWorker().getBlogBySpec(mBlogId, specOne, specTwo);
                                        } else {
                                            specNames2.get(i).setChecked(false);
                                            specText2.get(i).setBackgroundResource(R.drawable.shape_editor);
                                            specText2.get(i).setTextColor(Color.parseColor("#383838"));
                                        }
                                    }
                                }
                            });
                            specText2.add(tv);
                            flowLayout.addView(tv, lp0);
                        }
                    }
                }
                break;
            case BLOG_GET_BY_SPEC:
                HemaArrayResult<BlogDetailBySpec> bResult2 = (HemaArrayResult<BlogDetailBySpec>) baseResult;
                detailBySpec = bResult2.getObjects().get(0);
                if (isNull(detailBySpec.getImgurl()))
                    ImageUtils.loadSmalImage(mContext, blog.getImgurl(), attrImage);
                else
                    ImageUtils.loadSmalImage(mContext, detailBySpec.getImgurl(), attrImage);
                attrPrice.setText("¥" + uuUtils.formatAfterDot2(detailBySpec.getPrice()));
                tvPriceNew.setText("¥" + uuUtils.formatAfterDot2(detailBySpec.getPrice()));//将原商品价格也一起修改
                tvStore.setText("库存：" + detailBySpec.getLeftcount());
                tvCouponsCount.setText(uuUtils.formatAfterDot2(detailBySpec.getScore()) + "粮票");
                try {
                    int lefcount = Integer.parseInt(detailBySpec.getLeftcount());
                    numberSelector.setMaxValue(lefcount);
                    //2017.01.16 修改 start 这里默认最小值是0，可以触发无数量输入时的提示
//                    if (lefcount > 0) {
//                        numberSelector.setMinValue(1);
//                    }else {
//                        numberSelector.setMinValue(0);
//                    }
                    //2017.01.16 修改 end 这里默认最小值是0，可以触发无数量输入时的提示
                }catch (Exception e) {
                    e.printStackTrace();
                    numberSelector.setMaxValue(1);
                    XtomToastUtil.showShortToast(mContext, "商品库存未知");
                }
                break;
            case CART_ADD:
                XtomToastUtil.showShortToast(mContext, "加入购物车成功");
                //加入购物车后，将库存相应减去
//                try {
//                    int leftCount = Integer.parseInt(blog.getLeftcount());
//                    int buyCount = Integer.parseInt(netTask.getParams().get("buycount"));
//                    tvStore.setText("库存：" + (leftCount-buyCount));
//                    numberSelector.setMaxValue(leftCount-buyCount);
//                }catch (Exception e) {
//                    e.printStackTrace();
//                }
                if (user != null) {
                    String token = user.getToken();
                    getNetWorker().getCartCount(token);
                }
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.UPDATE_CART);
                EventBus.getDefault().post(msg);
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
                showTextDialog("获取商品信息失败！");
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                String oper = netTask.getParams().get("oper");
                // 操作	1添加 ，2取消 ;3：清空
                if (oper.equals("1")) {
                    showTextDialog("添加收藏失败!");
                } else {
                    showTextDialog("取消收藏失败!");
                }
                break;
            case REPLY_LIST:
                String page = netTask.getParams().get("page");
                if (page.equals("0")) {
                    refreshlayout.refreshFailed();
                } else {
                    refreshlayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取数据失败");
                break;
            case CART_ADD:
                XtomToastUtil.showShortToast(mContext, "加入购物车失败，" + baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
                showTextDialog("获取商品信息失败！");
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                String oper = netTask.getParams().get("oper");
                // 操作	1添加 ，2取消 ;3：清空
                if (oper.equals("1")) {
                    showTextDialog("添加收藏失败!");
                } else {
                    showTextDialog("取消收藏失败!");
                }
                break;
            case REPLY_LIST:
                String page = netTask.getParams().get("page");
                if (page.equals("0")) {
                    refreshlayout.refreshFailed();
                } else {
                    refreshlayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取数据失败，请稍后再试");
                break;
            case CART_ADD:
                XtomToastUtil.showShortToast(mContext, "加入购物车失败，请稍后再试");
                break;
        }
    }

    private void setData() {
        String collectFlag = blog.getCollectflag();
        if (collectFlag == null || collectFlag.equals("0")) {
            titleLove.setImageResource(R.drawable.star_while_stroke);
        } else {
            titleLove.setImageResource(R.drawable.star_while);
        }
        tvGoodsName.setText(blog.getName());
        tvPriceNew.setText("¥" + blog.getPrice());
        tvCouponsCount.setText(blog.getScore() + "粮票");
        tvPriceOld.setText("¥" + blog.getOldprice());
        tvPriceOld.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        tvSpec.setVisibility(View.GONE);
//		if (isNull(blog.getWeight()) || isNull(blog.getUnit())) {
//			tvSpec.setVisibility(View.GONE);
//		}else {
//			tvSpec.setText("规格："+blog.getWeight()+blog.getUnit());//规格这里，后台没有数据，先不显示
//		}
        // A级别	0：否；1：A级绿色；2：AA级绿色
        //2019.09.30修改，去掉有机、A级绿色食品、清真标签 start
//        if (!isNull(blog.getALevel()) && !blog.getALevel().equals("0")) {
//            tv_A.setVisibility(View.VISIBLE);
//            if (blog.getALevel().equals("1")) {
//                tv_A.setText("A级绿色食品");
//            } else if (blog.getALevel().equals("2")) {
//                tv_A.setText("AA级绿色食品");
//            }
//        }
//        if (!isNull(blog.getIslamflag()) && blog.getIslamflag().equals("1")) {
//            iv_muslim.setVisibility(View.VISIBLE);
//        }
//        if (!isNull(blog.getOrganicflag()) && blog.getOrganicflag().equals("1")) {
//            tv_organic.setVisibility(View.VISIBLE);
//        }
        //2019.09.30修改，去掉有机、A级绿色食品、清真标签 end
        //判断是否允许退货
        String returnflag = blog.getReturnflag();// 允许退货标记	0不允许 1允许
        tvTuihuo.setVisibility(View.VISIBLE);
        if (returnflag.equals("0")) {
            tvTuihuo.setText("拒绝退货");
            tvTuihuo.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_return_no, 0, 0, 0);
        } else {
            tvTuihuo.setText("允许退货");
            tvTuihuo.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_return, 0, 0, 0);
        }
        //设置运费、库存、销量
        tvFreight.setText("运费：" + blog.getExpressfee());
        tvStore.setText("库存：" + blog.getLeftcount());
        tvSellCount.setText("销量：" + blog.getSellcount());
        //显示商家信息
        ImageUtils.loadAvatar(mContext, blog.getAvatar(), ivMerchantAvatar);
        tvMerchantName.setText(blog.getNickname());
        String star = blog.getFarmer_starscore();
        if (!isNull(star)) {
            ratingBar.setRating(Float.parseFloat(star));
        }
        //商品详情
//		rbt_reply.setText("用户口碑("+blog.getReplycount()+")");
        tv_buycontent.setText( blog.getBuycontent());
        if (listView.getVisibility() == View.GONE)
            content_detail.setVisibility(View.VISIBLE);

        webview.setVisibility(View.VISIBLE);
        String sys_web_service = BaseApplication.getInstance().getSysInitInfo().getSys_web_service();
        String path = sys_web_service + "webview/parm/blogdetail_" + blog.getId();
        webview.loadUrl(path);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_img:
                if (BaseUtil.isLogin()) {
                    String token = user.getToken();
                    if ("0".equals(blog.getCollectflag())) {//未关注
                        getNetWorker().FolColOperate(token, "2", "1", blog.getId());
                    } else {//已关注
                        getNetWorker().FolColOperate(token, "2", "2", blog.getId());
                    }
                } else {
                    Intent itCart = new Intent(mContext, LoginActivity.class);
                    startActivity(itCart);
                }
                //这里不能使用登录回调，因为登陆后不能立即执行之前的操作，需要重新获取商品详情,然后再判断时取消收藏还是添加收藏
//                loginCallBack = new LoginUtil.LoginCallBack() {
//                    @Override
//                    public void onLogin() {
//                        String token = user.getToken();
//                        if ("0".equals(blog.getCollectflag())) {//未关注
//                            getNetWorker().FolColOperate(token, "2", "1", blog.getId());
//                        } else {//已关注
//                            getNetWorker().FolColOperate(token, "2", "2", blog.getId());
//                        }
//                        loginCallBack = null;
//                    }
//                };
//                LoginUtil.getInstance(mContext, loginCallBack);
                break;
            case R.id.title_right_img2:
                String sys_plugins = getApplicationContext().getSysInitInfo().getSys_plugins();
                String username = user == null ? "" : user.getUsername();
                String path = sys_plugins + "share/sdk.php?id=" + mBlogId + "&customflag=0&username=" + username;
                //图片url
                UMImage image = null;
                String imgUrl = blog.getImgurl();
                if (!isNull(imgUrl)) {
                    image = new UMImage(mContext, imgUrl);
                } else {
                    imgUrl = BaseUtil.getLogoImagePath(mContext);
                    image = new UMImage(mContext, BitmapFactory.decodeFile(imgUrl));
                }
                new ShareDialog(CmnProductionDetailActivity.this, "分享商品", blog.getName(), path, image)
                        .builder().show();
                break;
            case R.id.ll_return_top:
                scrollview.smoothScrollTo(0, 0);
                break;
            case R.id.layout_attribute:
                showAttr();
                break;
            case R.id.iv_consult:
//                if (BaseUtil.isLogin()) {
//                    String mQQNum = blog.getQq();
//                    if (isNull(mQQNum)) {
//                        XtomToastUtil.showShortToast(mContext, "对方没有指定QQ");
//                        break;
//                    }
//                    String url = "mqqwpa://im/chat?chat_type=wpa&uin=" + mQQNum;
//                    try {
//                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
//                    } catch (Exception e) {
//                        showTextDialog("打开QQ客户端失败\n请确保已经安装了QQ手机客户端");
//                        e.printStackTrace();
//                    }
//                } else {
//                    Intent itLogin = new Intent(mContext, LoginActivity.class);
//                    startActivity(itLogin);
//                }
                loginCallBack = new LoginUtil.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        String mQQNum = blog.getQq();
                        if (isNull(mQQNum)) {
                            XtomToastUtil.showShortToast(mContext, "对方没有指定QQ");
                            return;
                        }
                        String url = "mqqwpa://im/chat?chat_type=wpa&uin=" + mQQNum;
                        try {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        } catch (Exception e) {
                            showTextDialog("打开QQ客户端失败\n请确保已经安装了QQ手机客户端");
                            e.printStackTrace();
                        }
                        loginCallBack = null;
                    }
                };
                LoginUtil.getInstance(mContext, loginCallBack);
                break;
            case R.id.layout_go_cart:
                Intent it = new Intent();
                if (user == null) {
                    it.setClass(mContext, LoginActivity.class);
                } else {
                    it.setClass(mContext, ShoppingCartActivity.class);
                }
                startActivityForResult(it, REQUEST_GO_CART);
                break;
            case R.id.tv_add_cart:
                if (blog == null)
                    return;
                if (blog.getSaleflag().equals("0")) {
                    XtomToastUtil.showShortToast(mContext, "商品已下架");
                    return;
                }
                //获取库存
                int lefcount = 0;
                try {
                    lefcount = Integer.parseInt(blog.getLeftcount());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (lefcount < 1) {
                    XtomToastUtil.showShortToast(mContext, "库存不足");
                    return;
                }
                loginCallBack = new LoginUtil.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        attrSelectCallBack = new AttrSelectCallBack() {
                            @Override
                            public void onSelect() {
                                attrSelectCallBack = null;
                                int stock = 0;
                                String specId = "0";
                                if (detailBySpec != null) {
                                    if (!isNull(detailBySpec.getLeftcount())) {//如果是有规格的商品，那么去从规格商品详情中选择
                                        stock = Integer.parseInt(detailBySpec.getLeftcount());
                                    }
                                    specId = detailBySpec.getId();
                                } else {
                                    stock = Integer.parseInt(blog.getLeftcount());
                                }
                                if (stock > 0 && buyCount <= stock) {
                                    if (buyCount > 0)
                                        getNetWorker().cartAdd(user.getToken(), blog.getId(), buyCount + "", specId);
                                    else {
                                        numberSelector.setNumber(1);
                                        XtomToastUtil.showShortToast(mContext, "请选择购买数量");
                                        return;
                                    }
                                } else {
                                    XtomToastUtil.showShortToast(mContext, "库存不足");
                                    return;
                                }
                            }
                        };
                        //2016.10.17 start 修改：无论是否已经选择规格，点击加入购物车，都要再弹出一遍
                        //目的是对于一些没有规格的商品，可以选择购买数量。
//                        if (!isNull(blog.getOne_spec()) && isNull(specOne)) {
//                            showAttr();
//                            return;
//                        }
//                        if (!isNull(blog.getTwo_spec()) && isNull(specTwo)) {
//                            showAttr();
//                            return;
//                        }
//                        attrSelectCallBack.onSelect();
                        showAttr();
                        //2016.10.17 end
                        loginCallBack = null;
                    }
                };
                LoginUtil.getInstance(mContext, loginCallBack);
                break;
            case R.id.layout_merchant://商家详情
                if (blog == null)
                    break;
                if (blog.getType().equals("2")) {//平台商品
                    final String phone = blog.getMobile();
                    if (phone != null && !phone.isEmpty() && !phone.equals("无")) {
                        HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
                        hbDialog.setText("是否直接拨打" + phone + "?");
                        hbDialog.setLeftButtonText("取消");
                        hbDialog.setRightButtonText("拨打");
                        hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
                        hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                            @Override
                            public void onLeftButtonClick(HemaButtonDialog dialog) {
                                dialog.cancel();
                            }

                            @Override
                            public void onRightButtonClick(HemaButtonDialog dialog) {
                                dialog.cancel();
                                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(
                                        "tel:" + phone));
                                startActivity(intent);
                            }
                        });
                    } else {
                        XtomToastUtil.showShortToast(mContext, "对方没有提供电话号码");
                    }
                } else {//第三方商品
                    Intent itMerchant = new Intent(mContext, CmnMerchantDetailActivity.class);
                    itMerchant.putExtra("client_id", blog.getClient_id());
                    startActivity(itMerchant);
                }
                break;
            case R.id.iv_merchant_drawright:
                final String phone = blog.getMobile();
                if (phone != null && !phone.isEmpty() && !phone.equals("无")) {
                    HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
                    hbDialog.setText("是否直接拨打" + phone + "?");
                    hbDialog.setLeftButtonText("取消");
                    hbDialog.setRightButtonText("拨打");
                    hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
                    hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                        @Override
                        public void onLeftButtonClick(HemaButtonDialog dialog) {
                            dialog.cancel();
                        }

                        @Override
                        public void onRightButtonClick(HemaButtonDialog dialog) {
                            dialog.cancel();
                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(
                                    "tel:" + phone));
                            startActivity(intent);
                        }
                    });
                } else {
                    XtomToastUtil.showShortToast(mContext, "对方没有提供电话号码");
                }
                break;
            case R.id.tv_buy://立即购买
                if (blog == null)
                    return;
                if (blog.getSaleflag().equals("0")) {
                    XtomToastUtil.showShortToast(mContext, "商品已下架");
                    return;
                }
                //获取库存
                int lefcount2 = 0;
                try {
                    lefcount2 = Integer.parseInt(blog.getLeftcount());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (lefcount2 < 1) {
                    XtomToastUtil.showShortToast(mContext, "库存不足");
                    return;
                }
                loginCallBack = new LoginUtil.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        attrSelectCallBack = new AttrSelectCallBack() {
                            @Override
                            public void onSelect() {
                                attrSelectCallBack = null;
                                int stock = 0;
                                if (detailBySpec != null) {//有商品规格
                                    if (!isNull(detailBySpec.getLeftcount())) {
                                        stock = Integer.parseInt(detailBySpec.getLeftcount());
                                    }
                                } else {
                                    stock = Integer.parseInt(blog.getLeftcount());
                                }
                                if (stock > 0 && buyCount <= stock) {
                                    if (buyCount > 0) {
                                        Intent intent = new Intent(mContext, BuyConfirmActivityNew.class);
                                        intent.putExtra("keytype", "2");
                                        intent.putExtra("blog", blog);// 够买商品
                                        intent.putExtra("buycount", buyCount);// 够买商品数量
                                        intent.putExtra("blogDetail", detailBySpec);
                                        startActivity(intent);
                                    }else {
                                        numberSelector.setNumber(1);
                                        XtomToastUtil.showShortToast(mContext, "请选择购买数量");
                                        return;
                                    }
                                } else {
                                    XtomToastUtil.showShortToast(mContext, "库存不足");
                                }
                            }
                        };
                        //2016.10.17 start 修改：无论是否已经选择规格，点击加入购物车，都要再弹出一遍
                        //目的是对于一些没有规格的商品，可以选择购买数量。
//                        if (!isNull(blog.getOne_spec()) && isNull(specOne)) {
//                            showAttr();
//                            return;
//                        }
//                        if (!isNull(blog.getTwo_spec()) && isNull(specTwo)) {
//                            showAttr();
//                            return;
//                        }
//                        attrSelectCallBack.onSelect();
                        showAttr();
                        //2016.10.17 end
                        loginCallBack = null;
                    }
                };
                LoginUtil.getInstance(mContext, loginCallBack);
                break;
            case R.id.rbt_details://
                rbt_details.setTextColor(getResources().getColor(R.color.theme_orange));
                rbt_reply.setTextColor(getResources().getColor(R.color.text_color_dark_grey));
                details_line.setVisibility(View.VISIBLE);
                reply_line.setVisibility(View.INVISIBLE);
                content_detail.setVisibility(View.VISIBLE);
                listView.setVisibility(View.GONE);
                break;
            case R.id.rbt_reply://
                rbt_reply.setTextColor(getResources().getColor(R.color.theme_orange));
                rbt_details.setTextColor(getResources().getColor(R.color.text_color_dark_grey));
                reply_line.setVisibility(View.VISIBLE);
                details_line.setVisibility(View.INVISIBLE);
                content_detail.setVisibility(View.GONE);
                listView.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    //初始化商品属性
    private void initPropertyList() {
        attributes = (ArrayList<AttributeItems>) blog.getAttributeItems();
        if (attributes != null && attributes.size() > 0) {
            layoutProperty.removeAllViews();
            for (AttributeItems attribute : attributes) {
                View view = LayoutInflater.from(mContext).inflate(R.layout.production_detail_item, null);
                ((TextView) view.findViewById(R.id.name)).setText(attribute.getname());
                ((TextView) view.findViewById(R.id.content)).setText(attribute.getcontent());
                layoutProperty.addView(view);
            }
            layoutProperty.setVisibility(View.VISIBLE);
        }else
            layoutProperty.setVisibility(View.GONE);
    }

    //口碑
    private void replyList(String page) {
        getNetWorker().replyList("2", blog.getId(), page);
    }

    private void refreshData() {
        if (replyAdapter == null) {
            replyAdapter = new ReplyAdapter(mContext, replies);
            replyAdapter.setEmptyString("没有评价");
            listView.setAdapter(replyAdapter);
            BaseUtil.setListViewHeightBasedOnChildren(listView);
        } else {
            replyAdapter.setEmptyString("没有评价");
            replyAdapter.notifyDataSetChanged();
            BaseUtil.setListViewHeightBasedOnChildren(listView);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ADD_CART:
            case REQUEST_GO_CART:
                if (user != null) {
                    getNetWorker().getCartCount(user.getToken());
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private void showAttr() {
        if (attrDialog == null)
            initBlogSpec();
        else
            attrDialog.show();
    }

    /**
     * 初始化商品规格
     */
    private void initBlogSpec() {
        if (blog == null)
            return;
        View view = getLayoutInflater().inflate(R.layout.pop_select_goods_attr, null);
        attrDialog = new Dialog(mContext, R.style.ActionSheetDialogStyle);
        attrDialog.setContentView(view);
        attrDialog.setCanceledOnTouchOutside(true);
        attrDialog.setCancelable(true);
        attrImage = (ImageView) view.findViewById(R.id.iv_product);
        attrPrice = (TextView) view.findViewById(R.id.tv_price);
        LinearLayout layoutAttr = (LinearLayout) view.findViewById(R.id.layout_product_attr);
        TextView tvOK = (TextView) view.findViewById(R.id.tv_ok);
        numberSelector = (NumberSelectorLayout) view.findViewById(R.id.layout_number_selector);
        try {
            numberSelector.setMaxValue(Integer.parseInt(blog.getLeftcount()));
        }catch (Exception e) {
            e.printStackTrace();
            numberSelector.setMaxValue(1);
            XtomToastUtil.showShortToast(mContext, "商品库存未知");
        }
        //动态添加属性
        int oneDp = BaseUtil.dip2px(mContext, 1);
        LinearLayout.LayoutParams lp0 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp0.setMargins(oneDp * 5, 0, oneDp * 5, 0);
        if (!isNull(blog.getOne_spec())) {
            View view1 = getLayoutInflater().inflate(R.layout.layout_product_attr, null);
            TextView tvAttriName = (TextView) view1.findViewById(R.id.tv_attr_name);
            tvAttriName.setText("选择" + blog.getOne_spec());
            FlowLayout flowLayout = (FlowLayout) view1.findViewById(R.id.flowlayout);
//            if (specNames1.size() > 0) {//默认选中第一个
//                specNames1.get(0).setChecked(true);
//                specOne = specNames1.get(0).getOne_specname();
//                if (!isNull(blog.getTwo_spec()))//去获取二级规格
//                    getNetWorker().getBlogSpecName(blog_id, specOne);
//            }
            for (BlogSpecName spec : specNames1) {
                TextView tv = new TextView(mContext);
                tv.setText(spec.getOne_specname());
                tv.setPadding(oneDp * 15, oneDp * 3, oneDp * 15, oneDp * 3);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                tv.setTextColor(Color.parseColor("#383838"));
                tv.setGravity(Gravity.CENTER_VERTICAL);
                tv.setTag(spec);
                tv.setSingleLine();
                if (spec.isChecked()) {
                    tv.setBackgroundColor(Color.parseColor("#ffae40"));
                    tv.setTextColor(Color.parseColor("#ffffff"));
                } else {
                    tv.setBackgroundResource(R.drawable.shape_editor);
                    tv.setTextColor(Color.parseColor("#383838"));
                }
                tv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BlogSpecName spec1 = (BlogSpecName) v.getTag();
                        specOne = spec1.getOne_specname();
                        specTwo = "";
                        for (int i = 0; i < specNames1.size(); i++) {
                            if (specNames1.get(i).getOne_specname().equals(spec1.getOne_specname())) {
                                specNames1.get(i).setChecked(true);
                                specText1.get(i).setBackgroundColor(Color.parseColor("#ffae40"));
                                specText1.get(i).setTextColor(Color.parseColor("#ffffff"));
                                tvAttributeHint.setText("您当前选择的为："+specOne);
                                if (!isNull(blog.getTwo_spec()))//如果有二级属性
                                    getNetWorker().getBlogSpecName(mBlogId, specOne);
                                else
                                    getNetWorker().getBlogBySpec(mBlogId, specOne, "");
                            } else {
                                specNames1.get(i).setChecked(false);
                                specText1.get(i).setBackgroundResource(R.drawable.shape_editor);
                                specText1.get(i).setTextColor(Color.parseColor("#383838"));
                            }
                        }
                    }
                });
                specText1.add(tv);
                flowLayout.addView(tv, lp0);
            }
            layoutAttr.addView(view1);
        }
        if (!isNull(blog.getTwo_spec())) {
            View view1 = getLayoutInflater().inflate(R.layout.layout_product_attr, null);
            TextView tvAttriName = (TextView) view1.findViewById(R.id.tv_attr_name);
            tvAttriName.setText("选择" + blog.getTwo_spec());
            flowLayout = (FlowLayout) view1.findViewById(R.id.flowlayout);
            for (BlogSpecName spec : specNames2) {
                TextView tv = new TextView(mContext);
                tv.setText(spec.getTwo_specname());
                tv.setPadding(oneDp * 15, oneDp * 3, oneDp * 15, oneDp * 3);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                tv.setTextColor(Color.parseColor("#383838"));
                tv.setGravity(Gravity.CENTER_VERTICAL);
                tv.setTag(spec);
                tv.setSingleLine();
                if (spec.isChecked()) {
                    tv.setBackgroundColor(Color.parseColor("#ffae40"));
                    tv.setTextColor(Color.parseColor("#ffffff"));
                    tvAttributeHint.setText("您当前选择的为："+specOne+"，"+specTwo);
//                    tvAttribute.setText(specOne + "," + specTwo);
                } else {
                    tv.setBackgroundResource(R.drawable.shape_editor);
                    tv.setTextColor(Color.parseColor("#383838"));
                }
                tv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BlogSpecName spec2 = (BlogSpecName) v.getTag();
                        specTwo = spec2.getTwo_specname();
                        for (int i = 0; i < specNames2.size(); i++) {
                            if (specNames2.get(i).getTwo_specname().equals(spec2.getTwo_specname())) {
                                specNames2.get(i).setChecked(true);
                                specText2.get(i).setBackgroundColor(Color.parseColor("#ffae40"));
                                specText2.get(i).setTextColor(Color.parseColor("#ffffff"));
                                getNetWorker().getBlogBySpec(mBlogId, specOne, specTwo);
                            } else {
                                specNames2.get(i).setChecked(false);
                                specText2.get(i).setBackgroundResource(R.drawable.shape_editor);
                                specText2.get(i).setTextColor(Color.parseColor("#383838"));
                            }
                        }
                    }
                });
                specText2.add(tv);
                flowLayout.addView(tv, lp0);
            }
            layoutAttr.addView(view1);
        }

        ImageUtils.loadSmalImage(mContext, blog.getImgurl(), attrImage);
        attrPrice.setText("¥" + blog.getPrice());
        numberSelector.setNumber(buyCount);
        numberSelector.setMinValue(0);
        numberSelector.setEditable(true);
        numberSelector.setNumberSelectorListener(new NumberSelectorLayout.NumberSelectorListener() {
            @Override
            public void onNumberChanged(int curValue) {
                buyCount = curValue;
            }
        });
        tvOK.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!isNull(blog.getOne_spec()) && isNull(specOne)) {
                    XtomToastUtil.showShortToast(mContext, "请选择"+blog.getOne_spec());
                    return;
                }
                if (!isNull(blog.getTwo_spec()) && isNull(specTwo)) {
                    XtomToastUtil.showShortToast(mContext, "请选择"+blog.getTwo_spec());
                    return;
                }
                if (attrSelectCallBack != null) {
                    attrSelectCallBack.onSelect();
                }
                attrDialog.dismiss();
            }
        });

        Window dialogWindow = attrDialog.getWindow();
        dialogWindow.setGravity(Gravity.LEFT | Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.x = 0;
        lp.y = 0;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialogWindow.setAttributes(lp);
        attrDialog.show();
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            init();
            if (loginCallBack != null)
                loginCallBack.onLogin();
        }else if (msg.getType() == EventBusConfig.UPDATE_CART) {
            if (user != null) {
                String token = user.getToken();
                getNetWorker().getCartCount(token);
            }
        }else if (msg.getType() == EventBusConfig.UPDATE_PRODUCTION) {
            init();
        }
    }

    public interface AttrSelectCallBack {
        public void onSelect();//商品属性选择后的回调方法
    }
}
